package com.xing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.Utils.Result;
import com.xing.core.BaseServiceImpl;
import com.xing.dao.OssDao;
import com.xing.entity.OssEntity;
import com.xing.entity.OssFile;
import com.xing.server.impl.MinioTemplate;
import com.xing.service.OssService;
import com.xing.user.User;
import com.xing.utils.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2024/4/12 17:20
 */
@Service
public class OssServiceImpl extends BaseServiceImpl<OssDao, OssEntity> implements OssService {
    @Autowired
    private OssDao dao;
    @Autowired
    private MinioTemplate template;

    @Override
    public Long update(MultipartFile file) {
        String filename = file.getOriginalFilename();
        assert filename != null;
        OssFile ossFile = template.upLoadFile("test", filename.split("\\.")[0], file);
        OssEntity ossEntity = new OssEntity();
        ossEntity.setUrl(ossFile.getFilePath());
        ossEntity.setType(0);
        ossEntity.setUploadDate(new Date());
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ossEntity.setUserId(principal.getId());
        dao.insert(ossEntity);
        return ossEntity.getId();
    }

    @Override
    public PageData<OssEntity> ossEntityPageList(Integer pageNum, Integer pageSize) {
        // 封装查询条件
        LambdaQueryWrapper<OssEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(OssEntity.class)
                .eq(OssEntity::getDelFlag, 0);
        Page<OssEntity> page = new Page<OssEntity>(pageNum, pageSize);
        // 分页查询
        Page<OssEntity> ossEntityPage = dao.selectPage(page, lambdaQueryWrapper);
        // 封装返回信息
        return new PageData<>(ossEntityPage.getRecords(), ossEntityPage.getTotal());
    }

    @Override
    public Result delete(Long id) {
        // 封装查询条件
        LambdaQueryWrapper<OssEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(OssEntity.class)
                .eq(OssEntity::getId, id)
                .eq(OssEntity::getDelFlag, 0);
        // 查询判断文件是否存在
        OssEntity ossEntity = dao.selectOne(lambdaQueryWrapper);
        if (ossEntity == null) return new Result().err(467,"文件不存在");
        // 逻辑删除
        ossEntity.setDelFlag(1);
        int delete = dao.updateById(ossEntity);
        // 判断返回结果
        if (delete < 1) return new Result().err(456, "删除失败");
        return new Result().ok("删除成功");

    }
}
